package com.oet.web;



import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;

import com.oet.service.mail.EmailUtility;

/**
 * <code>Validator</code> for <code>YdkAccount</code> forms.
 *
 * @author Zhang Yu
 */
public class MngrAccountValidator {
	
//	public static final String telephoneRegex = 
//		"((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";

	private static final Pattern telephoneRegex = 
		Pattern.compile("((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)");
	
	public static boolean validateTel(String tel)
	{
		if (tel == null || tel.isEmpty())
		{
			return false;
		}
		Matcher m = telephoneRegex.matcher(tel);
		return m.matches();
		
	}
	
	public static void validate(MngrAccountForm account, Errors errors) {
		if (!StringUtils.hasLength(account.getName())) {
			errors.rejectValue("name", "required", "required");
		}
		if (!StringUtils.hasLength(account.getPassword())) {
			errors.rejectValue("password", "required", "required");
		}
		if (!StringUtils.hasLength(account.getRepeatedPw())) {
			errors.rejectValue("repeatedPw", "required", "required");
		}
		if (!account.getRepeatedPw().equals(account.getPassword())) {
			errors.rejectValue("repeatedPw", "not equal", "不一致");
		}
		if (!StringUtils.hasLength(account.getEmail())) {
			errors.rejectValue("email", "required", "required");
		}
		if (!EmailUtility.isValid(account.getEmail())) {
			errors.rejectValue("email", "invalid", "invalid");
		}
		if (account.getKeys().length == 0) {
			errors.rejectValue("keys", "required", "required");
		}
//		if (account.getRoleId() == null) {
//			errors.rejectValue("roleId", "required", "required");
//		}
		
	}

}
